import Taro from "@tarojs/taro";
import { useBoolean } from "ahooks";
import { Image, ImageProps, View } from "@tarojs/components";

import ByText from "./ByText";
import ByIcon from "./ByIcon";
import BySquare from "./BySquare";

import { ensureCompleteUrl, suffixUnit } from "@/utils";

type ByImageProps = {
  urls?: string[];
  className?: string;

  size?: number | string;
  preview?: boolean;
  showDelete?: boolean;

  // 是否显示长按菜单
  showmenu?: boolean;

  circle?: boolean;
} & Omit<ImageProps, "preview">;

type ByImageEvents = {
  onDelete?: () => void;
  onClick?: () => void;
};

export default ({
  src,
  mode,
  urls = [],
  size = 140,
  preview = true,
  circle = true,
  showDelete,
  className,
  onDelete,
  onClick,
}: ByImageProps & ByImageEvents) => {
  const url = ensureCompleteUrl(src);
  const [isError, { setTrue }] = useBoolean(false);

  return (
    <View
      className={`relative overflow-hidden ${circle ? "rounded-full" : "rounded-md"
        } ${className}`}
      style={`width:${suffixUnit(size)};height:${suffixUnit(size)}`}
      onClick={onClick}
    >
      {!src || isError ? (
        <View className="flex-center text-center h-full bg-page">
          <View>
            <ByIcon
              name={isError ? "ImgError" : "NoImg"}
              size={42}
              className="text-third"
            />
            {isError && (
              <ByText block size="xs" type="third">
                加载失败
              </ByText>
            )}
          </View>
        </View>
      ) : (
        <Image
          className="w-full h-full"
          src={url}
          mode={mode}
          onError={setTrue}
          onClick={() => preview && Taro.previewImage({ urls, current: src })}
        />
      )}

      {showDelete && (
        <BySquare
          size={40}
          icon="Delete"
          iconSize={22}
          className="absolute top-1 right-1 z-10 bg-[#fff]/75 text-error"
          onClick={onDelete}
        />
      )}
    </View>
  );
};
